"""
Case Type   : security-EqualityQuery
Case Name   : 通过JDBC（opengauss-jdbc-x.x.x.jar）创建加密表，执行加密表的预编译SQL语句
Create At   : 2023/10/12
Owner       : opentestcase003
Description :
    1.拷贝java脚本到主机，写入连接信息
    2.编译脚本
    3.执行脚本
Expect      :
    1.拷贝完成，写入信息成功
    2.编译成功
    3.执行成功
History     :
    Modified by peilinqian at 2025-1-22:优化用例配置$GAUSSHOME/etc/localkms路径步骤，排除app路径拼接错误问题
"""
import os
import unittest
from yat.test import Node
from yat.test import macro
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Common import Common
from testcase.utils.Logger import Logger


class Equality(unittest.TestCase):
    def setUp(self):
        self.logger = Logger()
        self.logger.info(f'-----{os.path.basename(__file__)} start-----')
        self.common = Common()
        self.sh_primy = CommonSH('PrimaryDbUser')
        self.primary_root = Node(node='PrimaryRoot')
        self.userNode = Node('PrimaryDbUser')
        self.jdbc_script = os.path.join('/', 'home', 'jdbc_security')
        self.java_name = 'jdbc_secret_equivalence_query_0001'
    
    def test_security(self):
        text = '----pre1:配置$GAUSSHOME/etc/localkms路径;expect:成功---'
        self.logger.info(text)
        mkdir_cmd1 = f'source {macro.DB_ENV_PATH};' \
                    f'if [ ! -d "$GAUSSHOME/etc/localkms" ];' \
                    f'then mkdir $GAUSSHOME/etc/localkms;fi'
        self.logger.info(mkdir_cmd1)
        mkdir_msg1 = self.userNode.sh(mkdir_cmd1).result()
        self.assertTrue(mkdir_msg1 == '' or 'File exists' in mkdir_msg1)
        mkdir_cmd2 = f'if [ ! -d "{self.jdbc_script}" ];' \
            f'then mkdir {self.jdbc_script};fi'
        self.logger.info(mkdir_cmd2)
        mkdir_msg2 = self.primary_root.sh(mkdir_cmd2).result()
        self.logger.info(mkdir_msg2)
        self.assertTrue(mkdir_msg2 == '' or 'File exists' in mkdir_msg2)
        
        text = '---step1:拷贝java脚本到主机，写入连接信息;expect:成功---'
        self.logger.info(text)
        jar_name, jar_path = self.common.get_jdbc('opengauss')
        self.primary_root.scp_put(jar_path,
                        f"{os.path.join(self.jdbc_script, jar_name)}")
        res2 = self.common.scp_file(self.primary_root,
                        f"{self.java_name}.java", self.jdbc_script)
        self.logger.info(res2)
        con_params = ['opengauss', self.primary_root.ssh_host,
                      self.userNode.db_port, self.userNode.db_name,
                      self.userNode.db_user, self.userNode.db_password,
                      'enable_ce=1']
        replace_content = ['postgresql', 'host_ip', 'db_port', 'database_name',
                           'conn_user', 'conn_passwd', 'url_params']
        i = 0
        while i < len(replace_content):
            exe_cmd1 = f"sed -i 's/{replace_content[i]}/{con_params[i]}/g' " \
                f"{os.path.join(self.jdbc_script, f'{self.java_name}.java')}"
            self.logger.info(exe_cmd1)
            msg1 = self.primary_root.sh(exe_cmd1).result()
            self.logger.info(msg1)
            self.assertEqual('', msg1, '执行失败' + text)
            i += 1
        check_cmd = f"cat " \
            f"{os.path.join(self.jdbc_script, f'{self.java_name}.java')}"
        check_msg = self.primary_root.sh(check_cmd).result()
        for content in con_params:
            self.assertIn(content, check_msg, '执行失败' + text)
        
        text = '---step2:编译脚本;expect:成功---'
        self.logger.info(text)
        exe_cmd2 = f"source {macro.DB_ENV_PATH};javac -encoding utf-8 -cp " \
            f"{os.path.join(self.jdbc_script, jar_name)} " \
            f"{os.path.join(self.jdbc_script, f'{self.java_name}.java')}"
        self.logger.info(exe_cmd2)
        msg2 = self.primary_root.sh(exe_cmd2).result()
        self.logger.info(msg2)
        self.assertEqual('', msg2, '执行失败:' + text)
        
        text = '---step3:执行脚本;expect:成功---'
        self.logger.info(text)
        exe_cmd3 = f"source {macro.DB_ENV_PATH};java -cp " \
            f"{os.path.join(self.jdbc_script, jar_name)}:" \
            f"{os.path.join(self.jdbc_script, jar_name)}:" \
            f"{self.jdbc_script} {self.java_name}"
        self.logger.info(exe_cmd3)
        msg3 = self.primary_root.sh(exe_cmd3).result()
        self.logger.info(msg3)
        self.assertIn('加密表查询成功', msg3, '执行失败:' + text)
        self.assertIn('预编译SQL语句执行成功', msg3, '执行失败:' + text)
        self.assertIn('Execution Succeeded', msg3, '执行失败:' + text)
    
    def tearDown(self):
        text = '----清理环境----'
        self.logger.info(text)
        clean_cmd = f"source {macro.DB_ENV_PATH};" \
                    f"rm -rf $GAUSSHOME/etc/localkms;" \
                    f"rm -rf {self.jdbc_script};" \
                    f"ls $GAUSSHOME/etc/localkms;" \
                    f"ls {self.jdbc_script}"
        clean_msg = self.primary_root.sh(clean_cmd).result()
        self.logger.info(clean_msg)
        self.assertTrue(clean_msg.count('No such file or directory') == 2,
                        text + '执行失败')
        self.logger.info(f'-----{os.path.basename(__file__)} end-----')
